package com.hnust.fx;

import com.hnust.MainApp;
import com.jfoenix.controls.JFXDecorator;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.Image;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;
import org.kordamp.ikonli.javafx.FontIcon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import static com.sun.javafx.application.LauncherImpl.launchApplication;
import java.util.function.Consumer;

@SuppressWarnings("WeakerAccess")
public abstract class AbstractJavaFxApplicationSupport extends Application {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaFxApplicationSupport.class);

    private static String[] savedArgs = new String[0];

    static Class<? extends AbstractFxmlView> savedInitialView;

    private static ConfigurableApplicationContext applicationContext;

    private static final Consumer<Throwable> errorAction = defaultErrorAction();

    static Image icon;

    @Override
    public void init() {
        try{
            applicationContext=SpringApplication.run(this.getClass(), savedArgs);
            LOGGER.info("获取springboot上下文对象："+applicationContext);
        }catch (Exception e){
            errorAction.accept(e);
        }
    }

    @Override
    public void start(final Stage stage) {
        try{
            GUIState.setStage(stage);
            loadIcon();
            switchView(savedInitialView);
        }catch (Exception e){
            errorAction.accept(e);
        }
    }

    public void loadIcon(){
        try{
            String s= MainApp.class.getResource("/image/app.png").toExternalForm();
            LOGGER.info("记载图标位置："+s);
            icon=new Image(s);
        }catch (Exception e){
            LOGGER.error("加载界面图标失败 ", e);
            errorAction.accept(e);
        }
    }

    public static void switchView(final Class<? extends AbstractFxmlView> view){
        GUIState.getStage().close();
        Stage stage=new Stage();
        stage.getIcons().add(icon);
        final AbstractFxmlView testView = applicationContext.getBean(view);
        JFXDecorator mainDecorator= new JFXDecorator(stage,testView.getView());
        Scene testScene=setDecoratorStyle(mainDecorator);
        stage.setScene(testScene);
        stage.show();
        GUIState.setScene(testScene);
        GUIState.setStage(stage);
    }

    private static Scene setDecoratorStyle(JFXDecorator mainDecorator) {
        mainDecorator.setCustomMaximize(true);
        mainDecorator.setTitle("教师端出卷系统");
        FontIcon fontIcon=new FontIcon("fab-windows");
        fontIcon.setIconColor(Paint.valueOf("#ffffff"));
        fontIcon.setIconSize(22);
        mainDecorator.setGraphic(fontIcon);
        mainDecorator.requestFocus();
        Scene scene = new Scene(mainDecorator);
        ObservableList<String> styleSheets=scene.getStylesheets();
        styleSheets.addAll(
                AbstractFxmlView.class.getResource("/css/jfoenix.css").toExternalForm());
        return scene;
    }

    private static Consumer<Throwable> defaultErrorAction() {
        return e -> {
            Alert alert = new Alert(AlertType.ERROR, "软件出错了，请稍后再重启试试");
            alert.showAndWait().ifPresent(response ->Platform.exit() );
        };
    }

    @Override
    public void stop() throws Exception {
        super.stop();
        if (applicationContext != null) {
            applicationContext.close();
        }
    }

    public static void launch(final Class<? extends Application> appClass,
            final Class<? extends AbstractFxmlView> view, final String[] args,boolean isLoading) {
        savedInitialView = view;
        savedArgs = args;
        if(isLoading){
            launchApplication(appClass,FxAppPreloader.class,args);
        }else{
            Application.launch(appClass, args);
        }
    }

}
